package com.damage.admin.service.impl;

import com.damage.admin.mapper.IEmployeeMapper;
import com.damage.admin.service.IEmployeeService;
import com.damage.common.config.DepartmentConfig;
import com.damage.common.entity.Employee;
import com.damage.common.exception.UniqueException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private IEmployeeMapper mapper;

    @Autowired
    private IdentityService identityService;

    @Value("${pageSize}")
    private Integer pageSize;

    @Override
    @Transactional
    public Integer newEmployee(Employee employee)
            throws UniqueException{
        Employee sqlEmployee = mapper.findByName(employee.getName());
        if (sqlEmployee != null) {
            //出现同名的员工
            throw new UniqueException("员工的名字已存在！");
        }
        //插入一个新的员工到数据库
        Integer result = mapper.insert(employee);
        //检查并添加为activiti的用户
        String userId = getActivitiUserId(employee.getId());
        List<User> users = identityService.createUserQuery().userId(userId).list();
        if (users.size() == 1) {
            //如果已经存在该用户，就更新用户的信息
            User user = users.get(0);
            user.setFirstName(employee.getName());
            user.setPassword(employee.getPassword());
            identityService.saveUser(user);

            //删除存在用户的membership
            List<Group> groups = identityService.createGroupQuery().groupMember(userId).list();
            for (Group group : groups) {
                identityService.deleteMembership(userId, group.getId());
            }

            //添加新的membership
            identityService.createMembership(userId, getDepartmentName(employee.getDepartment()));
        } else {
            //是新的用户
            User user = identityService.newUser(userId);
            user.setFirstName(employee.getName());
            user.setPassword(employee.getPassword());
            identityService.saveUser(user);
            //添加membership
            identityService.createMembership(userId, getDepartmentName(employee.getDepartment()));
        }
        return result;
    }

    @Override
    public PageInfo<Employee> findEmployee(Integer pageNum, Integer department,String name) {
        if (pageNum == null) {
            pageNum = 1;
        }
        PageHelper.startPage(pageNum,pageSize);
        PageInfo<Employee> pageInfo = null;
        if (department == null && Strings.isNullOrEmpty(name)){
            pageInfo = new PageInfo<Employee>(mapper.findAll());
        }else if (department == null){
            pageInfo = new PageInfo<Employee>(mapper.findLikeName(name));
        }else{
            pageInfo = new PageInfo<Employee>(mapper.findByDepartmentAndName(department,name));
        }
        return pageInfo;
    }

    @Override
    public PageInfo<Employee> findAll(Integer pageNum) {
        if (pageNum == null) {
            pageNum = 1;
        }
        PageHelper.startPage(pageNum,pageSize);
        PageInfo<Employee> pageInfo = new PageInfo<>(mapper.findAll());
        return pageInfo;
    }

    @Override
    public Employee findById(Integer id) {
        return mapper.findById(id);
    }

    @Override
    @Transactional
    public Integer update(Employee employee) {
        //更新员工
        Integer result = mapper.update(employee);
        //更新activiti相应的记录
        String userId = getActivitiUserId(employee.getId());
        User user = identityService.createUserQuery().userId(userId).singleResult();
        if (user != null){
            //修改名字
            String name = employee.getName();
            if (!Strings.isNullOrEmpty(name)){
                user.setFirstName(name);
            }
            //修改密码
            String password = employee.getPassword();
            if (!Strings.isNullOrEmpty(password)){
                user.setPassword(password);
            }
            identityService.saveUser(user);
            //修改所属部门
            Integer department = employee.getDepartment();
            Group group = identityService.createGroupQuery().groupMember(user.getId()).singleResult();
            identityService.deleteMembership(user.getId(),group.getId());
            identityService.createMembership(user.getId(),getDepartmentName(department));
        }
        return result;
    }

    @Override
    @Transactional
    public Integer deleteById(Integer id) {
        //删除员工
        Integer result = mapper.deleteById(id);
        //删除activiti相应的记录
        String userId = getActivitiUserId(id);
        User user = identityService.createUserQuery().userId(userId).singleResult();
        if (user != null){
            identityService.deleteUser(user.getId());
        }
        return result;
    }

    //通过部门的代号获得部门的名称
    private String getDepartmentName(Integer departmentNumber){
        Map<Integer, String> deptMap = DepartmentConfig.deptMap;
        String departmentName = deptMap.get(departmentNumber);
        return departmentName;
    }

//    //通过部门的名称获得部门的代号
//    private Integer getDepartmentNumber(String departmentName){
//        Map<Integer, String> deptMap = DepartmentConfig.deptMap;
//        Integer departmentCode = null;
//        Iterator<Map.Entry<Integer, String>> iterator = deptMap.entrySet().iterator();
//        while (iterator.hasNext()){
//            Map.Entry<Integer, String> entry = iterator.next();
//            if (departmentName.equals(entry.getValue())){
//                departmentCode =  entry.getKey();
//                break;
//            }
//        }
//        return departmentCode;
//    }

    //通过实体类id,获得相应Activiti的用户id
    private String getActivitiUserId(Integer id){
        StringBuffer sb = new StringBuffer("employee:");
        sb.append(id);
        String userId = sb.toString();
        return userId;
    }
}
